package cn.sdormitory.service.impl;

import cn.sdormitory.knowledgebase.dao.StudySkillsBatchExamDao;
import cn.sdormitory.knowledgebase.dao.StudySkillsBatchUserDao;
import cn.sdormitory.knowledgebase.dao.StudySkillsExamRecordDao;
import cn.sdormitory.knowledgebase.dto.HandPaperDto;
import cn.sdormitory.knowledgebase.pojo.*;
import cn.sdormitory.knowledgebase.vo.AppSkillsBatchUserVo;
import cn.sdormitory.knowledgebase.vo.AppUserAnswerRecordVo;
import cn.sdormitory.knowledgebase.vo.StudyQuestionsVo;
import cn.sdormitory.service.AppStudySkillsService;
import cn.sdormitory.knowledgebase.dao.StudySkillsDao;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class AppStudySkillsServiceImpl implements AppStudySkillsService {

    @Resource
    private StudySkillsDao studySkillsDao;
    @Resource
    private StudySkillsBatchUserDao studySkillsBatchUserDao;
    @Resource
    private StudySkillsBatchExamDao batchExamDao;
    @Resource
    private StudySkillsExamRecordDao studySkillsExamRecordDao;

    @Override
    public List<AppSkillsBatchUserVo> getSkillsBatchByUserId(Integer userId) {
        return studySkillsDao.getAppSkillsBatchByUserId(userId);
    }

    @Override
    public StudySkills getStudySkillsById(Integer id) {
        return studySkillsDao.selectById(id);
    }

    @Override
    public void completeLearning(Integer userId, Integer batchId) {
        LambdaUpdateWrapper<StudySkillsBatchUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(StudySkillsBatchUser::getSkillsBatchId,batchId);
        wrapper.eq(StudySkillsBatchUser::getUserId,userId);
        wrapper.set(StudySkillsBatchUser::getStudyStatus,true);
        studySkillsBatchUserDao.update(null,wrapper);
    }

    @Override
    public List<StudyQuestionsVo> getExamQuestionsById(Integer id) {
        StudySkills skills = studySkillsDao.selectById(id);
        //获取考试题数
        Integer examNum = skills.getExamNum();
        if(examNum == 0 ) {
            return null;
        }else {
            List<StudyQuestionsVo> questions = studySkillsDao.getAppExamQuestionsById(id);
            // 检查列表大小是否足够
            if (questions == null || questions.size() < examNum) {
                throw new IllegalArgumentException("考试题数分配错误！");
            }

            List<StudyQuestionsVo> result = new ArrayList<>();
            Random random = new Random();
            Set<Integer> selectedIndices = new HashSet<>();

            while (result.size() < examNum) {
                int index = random.nextInt(questions.size());
                if (selectedIndices.add(index)) { // 确保索引是唯一的
                    result.add(questions.get(index));
                }
            }

            for (StudyQuestionsVo studyQuestionsVo : result) {
                studyQuestionsVo.parseOption();
            }
            return result;
        }
    }

    @Override
    public List<StudyQuestionsVo> getExamQuestionsResultByExamId(Integer examId) {
        List<StudyQuestionsVo> result = studySkillsDao.getAppExamQuestionsResultByExamId(examId);
        for (StudyQuestionsVo studyQuestionsVo : result) {
            studyQuestionsVo.parseOption();
        }
        return result;
    }

    @Override
    @Transactional
    public Integer handPaper(HandPaperDto handPaperDto) {
        List<StudyQuestionsVo> answerList = handPaperDto.getStudyQuestionsVo();
        //插入批次考试总成绩
        StudySkillsBatchExam batchExam = new StudySkillsBatchExam();
        batchExam.setSkillsBatchId(handPaperDto.getBatchId());
        batchExam.setUserId(handPaperDto.getUserId());
        batchExam.setTotalQuestions(answerList.size()); //总题数
        batchExamDao.insert(batchExam);

        //插入考试记录详情
        int correct = 0;//正确答题数
        int mError = 0;//错误答题数
        int not = 0;//未答题数
        for (StudyQuestionsVo questionsVo : answerList) {
            StudySkillsExamRecord examRecord = new StudySkillsExamRecord();//创建考试记录对象
            examRecord.setExamId(batchExam.getId());
            examRecord.setQuestionsId(questionsVo.getId());//题目ID
            examRecord.setUserAnswer(questionsVo.getUserAnswer());//用户答案
            switch (questionsVo.getType()) {
                case 1://单选题
                    //判断答案是否正确
                    if (questionsVo.getAnswer().equals(questionsVo.getUserAnswer())) {//判断答案是否正确
                        correct++;
                        examRecord.setIsCorrect(true);
                    } else if (questionsVo.getUserAnswer().isEmpty()) {//用户答案为空 未作答题数 +1
                        not++;
                        examRecord.setIsCorrect(false);
                    } else {
                        mError++;
                        examRecord.setIsCorrect(false);
                    }
                    break;
                case 2://多选题
                    System.out.println("多选题");
                    break;
                case 3://判断题
                    System.out.println("判断题");
                    break;
                case 4://填空题
                    System.out.println("填空题");
                    break;
                case 5://问答题
                    System.out.println("问答题");
                    break;
                default:
                    System.out.println("未知题型");
                    break;
            }
            studySkillsExamRecordDao.insert(examRecord);
        }


        //判断用户是否通过考试
        boolean isPassed = false;
        if (correct == batchExam.getTotalQuestions()) {
            isPassed = true;
            //更新用户技能批次表
            LambdaUpdateWrapper<StudySkillsBatchUser> batchUserWrapper = new LambdaUpdateWrapper<>();
            batchUserWrapper.eq(StudySkillsBatchUser::getSkillsBatchId,handPaperDto.getBatchId())
                    .eq(StudySkillsBatchUser::getUserId,handPaperDto.getUserId())
                    .set(StudySkillsBatchUser::getIsPassed,true);
            studySkillsBatchUserDao.update(null,batchUserWrapper);
        }

        //更新考试批次表
        batchExam.setCorrectQuestions(correct);
        batchExam.setErrorQuestions(mError);
        batchExam.setNotQuestions(not);
        batchExam.setIsPassed(isPassed);
        batchExamDao.updateById(batchExam);
        return batchExam.getId();
    }

    @Override
    public StudySkillsBatchExam getExamById(Integer examId) {
        return batchExamDao.selectById(examId);
    }

    @Override
    public List<AppUserAnswerRecordVo> getUserAnswerRecordList(Integer userId) {
        return studySkillsDao.getAppUserAnswerRecordList(userId);
    }


}
